//
//  ComListViewController.m
//  HuiKaoClient
//
//  Created by Wang Li on 13-3-7.
//  Copyright (c) 2013年 龚 杰. All rights reserved.
//

#import "ComListViewController.h"
#import <QuartzCore/QuartzCore.h>
#import "ASIHTTPRequest.h"
#import "CJSONDeserializer.h"
#import "AppDelegate.h"
#import "ChartViewController.h"
#import "MainTabBarController.h"
@interface ComListViewController ()

@end

@implementation ComListViewController
@synthesize m_ProductID;
- (id)init
{
    if (self = [super init]) {
        // Custom initialization
        _CommDataArr = [[NSMutableArray alloc] init];
        tTotallHeight = 10;
    }
    return self;
}

-(void) dealloc
{
    [_ScrollView release];
    [_RightBtt release];
    [_BuysBtt release];
    [_NavBtt release];
    [m_ProductID release];
    [m_titleBttBarItem release];
    [super dealloc];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
//    UILabel* tNavTitleLab = (UILabel*)[self.navigationController.navigationBar viewWithTag:144];
//    [tNavTitleLab setText:@"图书商城"];
    
    m_titleBttBarItem = [[MainTabBarController setTitle:@"图书商城"] retain];

    
    _NavBtt = [UIButton buttonWithType:UIButtonTypeCustom];
    [_NavBtt setImage:[UIImage imageNamed:@"nav_back.png"] forState:UIControlStateNormal];
    [_NavBtt addTarget:self action:@selector(navPopPressed) forControlEvents:UIControlEventTouchUpInside];
    _NavBtt.frame =CGRectMake(4, 7, 50, 30);
    [_NavBtt retain];
    UILabel* tBackLab = [[UILabel alloc] initWithFrame:CGRectMake(14, 5, 30, 20)];
    [tBackLab setBackgroundColor:[UIColor clearColor]];
    [tBackLab setTextColor:[UIColor whiteColor]];
    [tBackLab setText:@"返回"];
    [tBackLab setFont:[UIFont systemFontOfSize:13]];
    [_NavBtt addSubview:tBackLab];
    [tBackLab release];
    
    _BuysBtt = [UIButton buttonWithType:UIButtonTypeCustom];
    [_BuysBtt setImage:[UIImage imageNamed:@"chart.png"] forState:UIControlStateNormal];
    _BuysBtt.frame =CGRectMake(240, 10, 24, 24);
    [_BuysBtt addTarget:self action:@selector(buysBttPressed) forControlEvents:UIControlEventTouchUpInside];
    [_BuysBtt retain];
    
    _RightBtt = [UIButton buttonWithType:UIButtonTypeCustom];
    [_RightBtt setImage:[UIImage imageNamed:@"orderlist.png"] forState:UIControlStateNormal];
    _RightBtt.frame =CGRectMake(286, 10, 24, 24);
    [_RightBtt addTarget:self action:@selector(orderBttPressed) forControlEvents:UIControlEventTouchUpInside];
    [_RightBtt retain];
    
    _ScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, self.view.frame.size.height-44)];
    _ScrollView.delegate = self;
    [_ScrollView setBackgroundColor:BACKGROUND_COLOR];
    [self.view addSubview:_ScrollView];
    
    _NowPage =1;
    NSString* tURLStr = [NSString stringWithFormat:@"%@ac=getRemark&product_id=%@&page=%d&pageSize=20",RequestCurrentURL,m_ProductID,_NowPage];
    [self requestDetailData:tURLStr];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void) viewWillAppear:(BOOL)animated
{
    [self.navigationController.navigationBar addSubview:_NavBtt];
    [self.navigationController.navigationBar addSubview:_BuysBtt];
    [self.navigationController.navigationBar addSubview:_RightBtt];
    [self.navigationController.navigationBar addSubview:m_titleBttBarItem];
}
-(void) viewWillDisappear:(BOOL)animated
{
    [_NavBtt removeFromSuperview];
    [_BuysBtt removeFromSuperview];
    [_RightBtt removeFromSuperview];
    [m_titleBttBarItem release];
}

-(void) navPopPressed
{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void) buysBttPressed
{
    ChartViewController* tChartVC = [[ChartViewController alloc] init];
    tChartVC.navigationItem.hidesBackButton =YES;
    [self.navigationController pushViewController:tChartVC animated:YES];
    [tChartVC release];
}


-(void) requestAddChartFinish:(ASIHTTPRequest*)request
{
    NSError* tError;
    NSString* tReqStr = [request responseString];
    NSLog(@"ads json data =%@",tReqStr);
    NSData *jsonData = [tReqStr dataUsingEncoding:NSUTF32BigEndianStringEncoding];
	NSDictionary* tDataDic = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:&tError];
    AppDelegate* tAppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
    if (tDataDic != nil) {
        int tErrorCode =[[tDataDic objectForKey:@"error_code"] intValue];
        if (tErrorCode == 0) {
            NSDictionary* tRealDataDic = [tDataDic objectForKey:@"data"];
            if ([[tRealDataDic objectForKey:@"result"] intValue] == 1) {
                [tAppDel showWithCustomView:@"加入购物车成功" detailText:@"" isCue:-1 delayTime:2];
            }else{
                [tAppDel showWithCustomView:@"加入购物车失败" detailText:@"" isCue:-1 delayTime:2];
            }
        }else{
            if ([tDataDic objectForKey:@"error_msg"] != nil) {
                [tAppDel showWithCustomView:[tDataDic objectForKey:@"error_msg"] detailText:@"" isCue:-1 delayTime:2];
            }else{
                [tAppDel showWithCustomView:@"数据错误" detailText:@"" isCue:YES delayTime:2];
            }
            
        }
    }
    [self hudWasHidden:nil];
}

-(void) requestDetailData:(NSString*)f_URL
{
    [self addHudLoad];
    _NowPage++;
    ASIHTTPRequest* tRequestPage = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:f_URL]];
    [tRequestPage setDelegate:self];
    [tRequestPage setDidFailSelector:@selector(requestDetailFail:)];
    [tRequestPage setDidFinishSelector:@selector(requestDetailFinish:)];
    [tRequestPage startAsynchronous];
}

-(void) requestDetailFail:(ASIHTTPRequest*)request
{
    _NowPage--;
    AppDelegate* tAppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
    [tAppDel showWithCustomView:@"网络错误" detailText:@"" isCue:YES delayTime:2];
    [self hudWasHidden:nil];
}
-(void) requestDetailFinish:(ASIHTTPRequest*)request
{
    NSError* tError;
    NSString* tReqStr = /*@"{\"error_code\":0,\"error_msg\":\"\",\"data\":{\"list\":[{\"user_id\":1,\"username\":\"\u533f\u540d\",\"remark\":4,\"content\":\"\u8bf7\u95ee2013\u5e74\u6cb3\u5357\u516c\u52a1\u5458\u8003\u8bd5\u590d\u4e60\u6559\u6750\u662f\u6700\u65b0\u7248\u7684\u5417\uff1f\",\"reply\":\"\u4f60\u597d\uff0c\u6559\u6750\u4e2d\u5fc3\u5728\u552e\u6559\u6750\u5168\u90e8\u4e3a\u6700\u65b0\u7248\uff0c\u8bf7\u653e\u5fc3\u8ba2\u8d2d\uff01\"},{\"user_id\":1,\"username\":\"\u533f\u540d\",\"remark\":4,\"content\":\"本姓胡，对清朝自称阮光平，是越南历史上一位著名军事人物，亦是西山朝第二代皇帝（年号光中），以军事才能著称于世。阮惠生于越南中南部的西山邑（在今越南平定省怀仁府安溪），当时属于郑阮纷争时期南方旧阮的领地之内。因不满旧阮政府里权臣当道，政局败坏，阮惠便与兄长阮岳\",\"reply\":\"本姓胡，对清朝自称阮光平，是越南历史上一位著名军事人物，亦是西山朝第二代皇帝（年号光中），以军事才能著称于世。阮惠生于越南中南部的西山邑（在今越南平定省怀仁府安溪），当时属于郑阮纷争时期南方旧阮的领地之内。因不满旧阮政府里权臣当道，政局败坏，阮惠便与兄长阮岳\"}]}}";//*/[request responseString];
    NSLog(@"ads json data =%@",tReqStr);
    NSData *jsonData = [tReqStr dataUsingEncoding:NSUTF32BigEndianStringEncoding];
	NSDictionary* tDataDic = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:&tError];
    if (tDataDic != nil) {
        int tErrorCode =[[tDataDic objectForKey:@"error_code"] intValue];
        if (tErrorCode == 0) {
            NSDictionary* tRealDataDic = [tDataDic objectForKey:@"data"];
            NSArray* tListArr = [tRealDataDic objectForKey:@"list"];
            int tLastCount = [_CommDataArr count];
            [_CommDataArr  addObjectsFromArray:tListArr];
            UIImage* tLStarImg = [UIImage imageNamed:@"star.png"];
            UIImage* tGStarImg = [UIImage imageNamed:@"star_gray.png"];
            for (NSDictionary* tDic in tListArr) {
                NSString* tNickName = [tDic objectForKey:@"username"];
                NSString* tContent = [tDic objectForKey:@"content"];
                int  tStart = [[tDic objectForKey:@"remark"] intValue];
                NSString* tReplyStr = [tDic objectForKey:@"reply"];
                
                int tSizeHeight = 0;
                int tTopHeight = 0;
                int tDownHeight = 0;
                
                UITextView* tContentView = [[UITextView alloc] initWithFrame:CGRectMake(5, 0, 300, 10)];
                [tContentView setBackgroundColor:[UIColor clearColor]];
                [tContentView setText:tContent];
                [_ScrollView addSubview:tContentView];
                [tContentView release];
                tSizeHeight += tContentView.contentSize.height;
                tTopHeight = tContentView.contentSize.height;
                [tContentView removeFromSuperview];
                tContentView = nil;
                
                
                UITextView* tInContentView = [[UITextView alloc] initWithFrame:CGRectMake(4, 0, 292, 10)];
                [tInContentView setBackgroundColor:[UIColor colorWithRed:1 green:248/255.f blue:228/255.f alpha:1]];
                tInContentView.layer.borderWidth =1;
                tInContentView.layer.borderColor = [UIColor colorWithRed:252/255.f green:226/255.f blue:173/255.f alpha:1].CGColor;
                [tInContentView setText:[NSString stringWithFormat:@"管理员回复：%@",tReplyStr]];
                [_ScrollView addSubview:tInContentView];
                [tInContentView release];
                tSizeHeight += tInContentView.contentSize.height;
                tDownHeight = tInContentView.contentSize.height;
                [tInContentView removeFromSuperview];
                
                tSizeHeight+= 54;
                
                UIView* tRectView = [[UIView alloc] initWithFrame:CGRectMake(10, tTotallHeight, 300, tSizeHeight)];
                tRectView.layer.borderColor = [UIColor lightGrayColor].CGColor;
                tRectView.layer.borderWidth =1;
                tRectView.layer.cornerRadius =4.f;
                [tRectView setBackgroundColor:[UIColor whiteColor]];
                [_ScrollView addSubview:tRectView];
                [tRectView release];
                
                tContentView = [[UITextView alloc] initWithFrame:CGRectMake(5, 44, 300, tTopHeight)];
                [tContentView setBackgroundColor:[UIColor clearColor]];
                [tContentView setText:tContent];
                [tRectView addSubview:tContentView];
                [tContentView release];
                
                
                CALayer* tRectLayer = [CALayer layer];
                tRectLayer.frame =CGRectMake(8, 44+tTopHeight-4, 284, tDownHeight+2);
                [tRectLayer setBackgroundColor:[UIColor colorWithRed:1 green:248/255.f blue:228/255.f alpha:1].CGColor];
                tRectLayer.borderWidth =1;
                tRectLayer.borderColor = [UIColor colorWithRed:252/255.f green:226/255.f blue:173/255.f alpha:1].CGColor;
                [tRectView.layer addSublayer:tRectLayer];
                
                tInContentView = [[UITextView alloc] initWithFrame:CGRectMake(4, 44+tTopHeight, 292, tDownHeight)];
                [tInContentView setBackgroundColor:[UIColor clearColor]];
                [tInContentView setText:[NSString stringWithFormat:@"                     %@",tReplyStr]];
                [tRectView addSubview:tInContentView];
                [tInContentView release];
                
                UILabel* tGLLab = [[UILabel alloc] initWithFrame:CGRectMake(12, 44+tTopHeight-3, 100, 20)];
                [tGLLab setTextColor:[UIColor colorWithRed:242/255.f green:155/255.f blue:31/255.f alpha:1]];
                [tGLLab setBackgroundColor:[UIColor clearColor]];
                [tGLLab setFont:[UIFont systemFontOfSize:12]];
                [tGLLab setText:@"管理员回复："];
                [tRectView addSubview:tGLLab];
                [tGLLab release];
                
                UILabel* tNameLab = [[UILabel alloc] initWithFrame:CGRectMake(8, 10, 100, 20)];
                [tNameLab setBackgroundColor:[UIColor clearColor]];
                [tNameLab setText:tNickName];
                [tRectView addSubview:tNameLab];
                [tNameLab release];
                
                
                
                for (int i=0; i<5; i++) {
                    UIImageView* tStarImgView =[[UIImageView alloc] initWithFrame:CGRectMake(170+i*25, 6, 24, 24)];
                    if (i<tStart) {
                        [tStarImgView setImage:tLStarImg];
                    }else{
                        [tStarImgView setImage:tGStarImg];
                    }
                    [tRectView addSubview:tStarImgView];
                    [tStarImgView release];
                }
                
                UIImageView* tImgView = [[UIImageView alloc] initWithFrame:CGRectMake(1, 38, 298, 1)];
                [tImgView setImage:[UIImage imageNamed:@"xline.png"]];
                [tRectView addSubview:tImgView];
                [tImgView release];
                
                tTotallHeight+= tSizeHeight;
                tTotallHeight+=10;
            }
            int tTmpeH = tTotallHeight;
            if (tTmpeH <= _ScrollView.frame.size.height) {
                tTmpeH= _ScrollView.frame.size.height+1;
            }
            [_ScrollView setContentSize:CGSizeMake(320, tTmpeH)];
        }else{
            AppDelegate* tAppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
            if ([tDataDic objectForKey:@"error_msg"] != nil) {
                [tAppDel showWithCustomView:[tDataDic objectForKey:@"error_msg"] detailText:@"" isCue:YES delayTime:2];
            }else{
                [tAppDel showWithCustomView:@"数据错误" detailText:@"" isCue:YES delayTime:2];
            }
            
        }
    }
    [self hudWasHidden:nil];
}
#pragma mark -
#pragma mark MBProgressHUDDelegate
- (void)hudWasHidden:(MBProgressHUD *)hud{
	[_MBHUD removeFromSuperview];
    _MBHUD.delegate = nil;
	[_MBHUD release];
	_MBHUD=nil;
}

-(void) addHudLoad{
	if (_MBHUD == nil) {
		_MBHUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
		// Add HUD to screen
		[self.navigationController.view addSubview:_MBHUD];
		// Regisete for HUD callbacks so we can remove it from the window at the right time
		_MBHUD.delegate = self;
		_MBHUD.labelText = @"请求数据中...";
		[_MBHUD show:YES];
	}
}


#pragma mark -
#pragma mark UIScrollViewDelegate
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    int tPosyH =scrollView.contentSize.height-scrollView.frame.size.height;
    if (tPosyH < 0) {
        tPosyH = 0;
    }
    if (scrollView.contentOffset.y > tPosyH+30) {
        NSString* tURLStr = [NSString stringWithFormat:@"%@ac=getRemark&product_id=%@&page=%d&pageSize=20",RequestCurrentURL,m_ProductID,_NowPage];
        [self requestDetailData:tURLStr];
    }
    
}
@end
